/*
 * Copyright 2007 David R Kirkland 
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");  
 * you may not use this file except in compliance with the License. 
 * You may obtain a copy of the License at 
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0 
 * 
 * Unless required by applicable law or agreed to in writing, software 
 * distributed under the License is distributed on an "AS IS" BASIS, 
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
 * See the License for the specific language governing permissions and 
 * limitations under the License.
 */

using System;
using System.Collections.Generic;

namespace NetSpider.Retrieval.Policies
{
    public abstract class RetrievalPolicyComposite : RetrievalPolicy
    {
        protected readonly List<RetrievalPolicy> _policies;

        public RetrievalPolicyComposite(IEnumerable<RetrievalPolicy> policies, string[] supportedUriSchemas)
        {
            _policies = new List<RetrievalPolicy>(policies);
        }

        protected RetrievalPolicyComposite()
        {
            _policies = new List<RetrievalPolicy>();
        }

        public override RetrievalPolicy[] GetPolicyItems()
        {
            return _policies.ToArray();
        }

        public override RetrievalDecision OnBeforeRetrieval(string uri)
        {
            RetrievalDecision winningDecision = RetrievalDecision.ContinueFetching;
            foreach (RetrievalPolicy policy in _policies)
            {
                RetrievalDecision decision = policy.OnBeforeRetrieval(uri);
                winningDecision = GetWinningDecision(decision, winningDecision);
            }
            return winningDecision;
        }

        public override RetrievalDecision OnRetrievalProgress(long bytes)
        {
            RetrievalDecision winningDecision = RetrievalDecision.ContinueFetching;
            foreach (RetrievalPolicy policy in _policies)
            {
                RetrievalDecision decision = policy.OnRetrievalProgress(bytes);
                winningDecision = GetWinningDecision(decision, winningDecision);
            }

            return winningDecision;
        }

        private static RetrievalDecision GetWinningDecision(RetrievalDecision decision, RetrievalDecision winningDecision)
        {
            if (decision.Priority > winningDecision.Priority &&
                decision.ScheduleRetryFor > winningDecision.ScheduleRetryFor)
            {
                winningDecision = decision;
            }
            return winningDecision;
        }

        private static double ConvertBytesToKb(long bytes)
        {
            double kb = Convert.ToDouble(bytes)/1024F;
            return kb;
        }

       
        public override string[] GetSupportedUriSchemas()
        {
            throw new NotImplementedException();
        }
    }
}
